package com.video.main_video.common.utils;

import com.idrsolutions.image.png.PngCompressor;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.logging.log4j.Logger;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Base64;

public class ImgUtils {

    public static void main(String[] args) throws Exception {
//        Path path = Paths.get("xx.txt");
//        File file=new File("wdx\\");
//        System.out.println(System.currentTimeMillis());
//        file.mkdir();

        String s = compressImageByFile(new File("cda19e64a3fd473eb099e764fff761d3\\11-02-2023\\1676095486550.png"));

        System.out.println(s);


    }

    /***
     *
     * @param text
     * @throws IOException
     * @desc base64 解析为图片
     */
    public static String base64toPng(String text,String path) throws IOException {
        //获取解码器
        Base64.Decoder decoder = Base64.getDecoder();
        //选择文件保存的位置
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
        LocalDate date = LocalDate.now(); // get the current date
        path=path+"\\"+date.format(formatter);
        String filePath = generaPath(path);
        String fileName = System.currentTimeMillis() + ".png";
        try (FileOutputStream fileOutputStream = new FileOutputStream(filePath+"\\"+fileName)) {
            //写入
            fileOutputStream.write(decoder.decode(text));
        } catch (Exception e) {
            e.printStackTrace();
            fileName = null;
        }
        //关闭流
        return filePath+"\\"+fileName;
    }

    public static String generaPath(String path){
        File file=new File(path);
        if (file.exists()){
            return path;
        }
        file.mkdirs();
        return path;
    }
    /**
     * 压缩jpg图片,返回base64字符串
     * sourceFile: 源文件;
     */
    public static String compressImageByFile(File sourceFile) throws Exception {
//        log.info("原文件大小:[{}]",sourceFile.length());
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            //大于500K进行压缩:
            if (sourceFile.length() > 500 * 1024) {
                String fileName = sourceFile.getName();
                String prefix = fileName.substring(fileName.lastIndexOf(".")+1);
                if ("png".equals(prefix.toLowerCase())){
                    PngCompressor.compress(sourceFile,sourceFile);
                }else {
                    //sourceFile = getCompressFile(sourceFile,0.15f);
                    Thumbnails.of(sourceFile).scale(1f).outputQuality(0.1f).toFile(sourceFile);
                }
//                log.info("文件格式:[{}] -- 压缩后文件大小:[{}]",prefix,sourceFile.length());
            }

            in = new FileInputStream(sourceFile);
            out = new ByteArrayOutputStream();
            int read = 0;
            byte[] buffer = new byte[1024];
            while ((read = in.read(buffer, 0, 1024)) != -1) {
                out.write(buffer, 0, read);
            }
            return Base64.getEncoder().encodeToString(out.toByteArray());
        } catch (IOException e) {
            throw e;
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null){
                out.close();
            }
        }
    }
}